package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.log.MyLog;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @RequestMapping("/page")
    public R<Page> getPage(Integer page, Integer pageSize, String name) {
        return dishService.getPage(page, pageSize, name);
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping

    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @Transactional
    @PutMapping

    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }


    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional

    public R<String> delete(@RequestParam List<Long> ids) {
        //查询菜品状态,确认是否可以删除
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId, ids);
        lqw.eq(Dish::getStatus, 1);
        int count = dishService.count(lqw);
        if (count > 0) {
            throw new CustomException("启售状态的菜品不能删除");
        }
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getDishId, ids);
        int count1 = setmealDishService.count(wrapper);

        if (count1 > 0) {
            throw new CustomException("套餐中存在菜品,不能删除");
        }

        LambdaQueryWrapper<DishFlavor> query = new LambdaQueryWrapper<>();
        query.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(query);
        dishService.removeByIds(ids);
        return R.success("删除成功!");
    }

    /**
     * 套餐管理页面,添加套餐里面 , 根据条件查询对应的菜品数据,将菜品口味一起返回
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getList(Dish dish) {
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据分类id精确查询
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件,判断状态为起售的菜品   1
        lqw.eq(Dish::getStatus, 1);
        //模糊查询
        lqw.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        //添加排序,按sort正序排序,按updateTime倒序排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> dishList = dishService.list(lqw);

        dishDtoList = dishList.stream().map(dishItem -> {
            DishDto dishDto = new DishDto();
            //将dish中的基本信息拷贝到dishDto中
            BeanUtils.copyProperties(dishItem, dishDto);
            //创建构造器
            LambdaQueryWrapper<DishFlavor> dishFlavorLqw = new LambdaQueryWrapper<>();
            //查询口味表中的菜品id与菜品表的id比较
            dishFlavorLqw.eq(DishFlavor::getDishId, dishItem.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLqw);
            //设置dishdto中的口味属性
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,24, TimeUnit.HOURS);

        return R.success(dishDtoList);
    }

    @Transactional
    /**
     * 修改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")

    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.in(SetmealDish::getDishId, ids);
        //比对setmealdish表中dishid和 ids比对
        int count = setmealDishService.count(lqw);
        //如果count>0,说明套餐中存在要修改的菜品,抛出异常,不能修改
        if (count > 0) {
            throw new CustomException("套餐中包含菜品,不能修改");
        }
        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus, status);
        wrapper.in(Dish::getId, ids);
        dishService.update(wrapper);
        return R.success("Success");
    }
}
